import sqlite3
from logger import CLogger

class CField:
    def __init_(self):
        self.m_name = ''
        self.m_type = ''
        self.m_value = ''
        return
    
    def __del__(self):
        return
    
class CTable:
    def __init__(self):
        self.m_name = ''
        self.m_indexDict = {}
        self.m_fieldDict = {}
        return
        
    def __del__(self):
        return
        
class CRecord:
    def __init__(self):
        self.m_fieldDict = {}
        return
        
    def __del__(self):
        return

class CSqlLite3Api:
    def __init__(self):
        self.m_conn = sqlite3.connect(":memory:")
        self.m_cursor = self.m_conn.cursor()
        return 
    
    def __del__(self):
        return
    
    def createTable(self,strTableName,strFieldNameList):
        strFieldsInSql = ''
        for fieldName in strFieldNameList:
            strFieldsInSql = strFieldsInSql + fieldName + ','
        strFieldsInSql = strFieldsInSql[0:len(strFieldsInSql)-1]
        strSql = 'create table %s(%s)'%(strTableName,strFieldsInSql)
        CLogger.writeInfLog('exec sql: %s'%(strSql))
        self.m_cursor.execute(strSql)
    
    def insertRecord(self,strTableName,fieldList):
        strFieldsInSql = ''
        for field in fieldList:
            strFieldsInSql = strFieldsInSql + field.m_name + ','
        strFieldsInSql = strFieldsInSql[0:len(strFieldsInSql)-1]
        strValuesInSql = ''
        for field in fieldList:
            strValuesInSql = strValuesInSql + '\'' + field.m_value + '\'' + ','
        strValuesInSql = strValuesInSql[0:len(strValuesInSql)-1]
        strSql = 'insert into %s(%s) values(%s)'%(strTableName,strFieldsInSql,strValuesInSql)
        CLogger.writeInfLog('exec sql: %s'%(strSql))
        self.m_cursor.execute(strSql)
    
    def getRecordsByKey(self,strTableName,keyFieldList,strToFetchFieldNameList):
        strFieldsInSql = ''
        for strFieldName in strToFetchFieldNameList:
            strFieldsInSql = strFieldsInSql + strFieldName + ','
        strFieldsInSql = strFieldsInSql[0:len(strFieldsInSql)-1]
        strKeysInsql = ''
        for keyField in keyFieldList:
            strKeysInsql = strKeysInsql + '%s = \'%s\' and'%(keyField.m_name,keyField.m_value)
        strKeysInsql = strKeysInsql[0:len(strKeysInsql)-4]
        strSql = 'select %s from %s where %s;'%(strFieldsInSql,strTableName,strKeysInsql)
        CLogger.writeInfLog('exec sql: %s'%(strSql))
        self.m_cursor.execute(strSql)
        return  self.m_cursor.fetchall() 
        